
Ext.namespace("Addama.jcr.RepoManager");

Addama.jcr.RepoManager = function() {

    // private variables
    new Ext.data.JsonStore({
        storeId: "repositories",
        url: "/addama-rest/primary-repo/path/sessions?PROJECTION=label",
        root: "children",
        fields: ["name", "label", "uri"],
        sortInfo: {
            field: "name",
            direction: "ASC"
        }
    });

    var readOnlyStyle = "background:transparent;border:none;";

    // private functions
    function onRepoSelect() {
        var uri = getSelectedRepoURI();
        if (!uri) return;
        Ext.Ajax.request({
            url: uri,
            method: "get",
            success: function(o) {
                var json = Ext.decode(o.responseText);
                if (json) updateRepoProperties(json);
            }
       });
    }

    function onAddRepo() {
        var win = new Ext.Window({
            title: "Add Repository",
            closable: false,
            modal: true,
            width: 400,
            autoHeight: true,
            items: [
                new Ext.form.FormPanel({
                    border: false,
                    items: [
                        new Ext.form.FieldSet({
                            autoHeight: true,
                            border: false,
                            items: [
                                new Ext.form.TextField({
                                    id: "repoNameField",
                                    fieldLabel: "Name",
                                    name: "name",
                                    width: 150,
                                    allowBlank: false
                                }),
                                new Ext.form.TextField({
                                    id: "repoTypeField",
                                    fieldLabel: "Type",
                                    name: "type",
                                    value: "jackrabbit",
                                    width: 150,
                                    allowBlank: false
                                }),
                                new Ext.form.TextField({
                                    id: "repoHostField",
                                    fieldLabel: "Host",
                                    name: "host",
                                    width: 150,
                                    allowBlank: false
                                }),
                                new Ext.form.TextField({
                                    id: "repoPortField",
                                    fieldLabel: "Port",
                                    name: "port",
                                    width: 150,
                                    allowBlank: false
                                }),
                                new Ext.form.TextField({
                                    id: "repoUsernameField",
                                    fieldLabel: "Username",
                                    name: "username",
                                    width: 150,
                                    allowBlank: false
                                }),
                                new Ext.form.TextField({
                                    id: "repoPasswordField",
                                    fieldLabel: "Password",
                                    name: "password",
                                    inputType: "password",
                                    width: 150,
                                    allowBlank: false
                                })
                            ]
                        })
                    ],
                    buttons: [{
                        text: "Add",
                        handler: function() {
                            var name = Ext.getCmp("repoNameField").getValue();
                            var type = Ext.getCmp("repoTypeField").getValue();
                            var host = Ext.getCmp("repoHostField").getValue();
                            var port = Ext.getCmp("repoPortField").getValue();
                            var username = 
                                Ext.getCmp("repoUsernameField").getValue();
                            var password = 
                                Ext.getCmp("repoPasswordField").getValue();
                            if (name === '' ||
                                type === '' ||
                                host === '' ||
                                port === '' ||
                                username === '' ||
                                password === '') {
                                    return;
                            }
                            Addama.jcr.RepoManager.addRepository({
                                name: name,
                                type: type,
                                host: host,
                                port: port,
                                username: username,
                                password: password,
                                callback: function() {
                                    refreshRepoList();
                                }
                            });
                            win.close();
                        }
                    },{
                        text: "Cancel",
                        handler: function() {
                            win.close();
                        }
                    }]
                })
            ]
        });
        win.show();
    }

    function onRemoveRepo() {
        var uri = getSelectedRepoURI();
        if (!uri) return;
        Addama.jcr.RepoManager.removeRepository({
            uri: uri,
            callback: function() {
                refreshRepoList();
            }
        });
    }

    function onSetLabel() {
        var uri = getSelectedRepoURI();
        if (!uri) return;
        Addama.jcr.RepoManager.renameRepository({
            uri: uri,
            callback: function() {
                refreshRepoList();
            }
        });
    }

    function refreshRepoList() {
        Ext.StoreMgr.lookup("repositories").reload();
    }

    function updateRepoProperties(o) {
        Ext.getCmp("repoNameProp").setValue(o.name);
        Ext.getCmp("repoSessionProp").setValue(o.session);
        Ext.getCmp("repoUsernameProp").setValue(o.user);
        Ext.getCmp("repoPasswordProp").setValue(o.passwd);
    }

    function getSelectedRepoURI() {
        var grid = Ext.getCmp("reposGrid");
        var record = grid.getSelectionModel().getSelected();
        return (record ? record.data.uri : undefined);
    }

    // public
    return {
        // public properties

        // public methods

        addRepository: function(o) {
            var json = {
                host: o.host,
                port: o.port,
                session: "rmi://" + o.host + ":" + o.port + "/" + o.type,
                user: o.username,
                passwd: o.password
            };
            Ext.Ajax.request({
                url: "/addama-rest/primary-repo/path/sessions/" + o.name + "/create",
                method: "post",
                params: {
                    JSON: Ext.encode(json)
                },
                success: o.callback,
                failure: function(resp) {
                    var msg;
                    if (resp.status == 409) {
                        msg = "Repository with name '" + o.name + "' already exists.";
                    }
                    else {
                        msg = "An error occurred while adding repository '" + o.name + "'.";
                    }
                    Ext.MessageBox.show({
                        title: "Error",
                        msg: msg,
                        buttons: Ext.MessageBox.OK,
                        icon: Ext.MessageBox.ERROR
                    });
                }
            });
        },

        removeRepository: function(o) {
            Ext.Ajax.request({
                url: o.uri + "/delete",
                method: "post",
                success: o.callback,
                failure: function() {
                    Ext.MessageBox.show({
                        title: "Error",
                        msg: "An error occurred while removing the repository.",
                        buttons: Ext.MessageBox.OK,
                        icon: Ext.MessageBox.ERROR
                    });
                }
            });
        },

        renameRepository: function(o) {
            var win = new Ext.Window({
                title: "Rename Repository",
                closable: false,
                modal: true,
                width: 400,
                autoHeight: true,
                items: [
                    new Ext.form.FormPanel({
                        border: false,
                        items: [
                            new Ext.form.FieldSet({
                                autoHeight: true,
                                border: false,
                                items: [
                                    new Ext.form.TextField({
                                        id: "renameField",
                                        fieldLabel: "New Name",
                                        name: "rename",
                                        width: 150,
                                        allowBlank: false
                                    })
                                ]
                            })
                        ],
                        buttons: [{
                            text: "Save",
                            handler: function() {
                                var rename = Ext.getCmp("renameField").getValue();
                                Ext.Ajax.request({
                                    url: o.uri,
                                    method: "post",
                                    params: {
                                        JSON: Ext.encode({label: rename})
                                    },
                                    success: o.callback,
                                    failure: function() {
                                        Ext.MessageBox.show({
                                            title: "Error",
                                            msg: "An error occurred while renaming the repository",
                                            buttons: Ext.MessageBox.OK,
                                            icon: Ext.MessageBox.ERROR
                                        });
                                    }
                                });
                                win.close();
                            }
                        },{
                            text: "Cancel",
                            handler: function() {
                                win.close();
                            }
                        }]
                    })
                ]
            });
            win.show();
        },

        loadRepositories: function() {
            Ext.StoreMgr.lookup("repositories").load();
            
            new Ext.Panel({
                width: 400,
                height: 400,
                border: false,
                renderTo: "content-repositories",
                layout: "border",
                items: [{
                    region: "center",
                    title: "Repositories",
                    width: 200,
                    height: 200,
                    autoScroll: true,
                    split: true,
                    items: [
                        new Ext.grid.GridPanel({
                            id: "reposGrid",
                            store: Ext.StoreMgr.lookup("repositories"),
                            columns: [
                                { id: "name", header: "Name", sortable: true, dataIndex: "name" },
                                { id: "label", header: "Label", sortable: true, dataIndex: "label" }
                            ],
                            viewConfig: {
                                forceFit: true
                            },
                            sm: new Ext.grid.RowSelectionModel({
                                singleSelect: true
                            }),
                            stripeRows: true,
                            autoHeight: true,
                            border: false,
                            hideHeaders: true,
                            listeners: {
                                rowClick: onRepoSelect
                            }
                        })
                    ],
                    tbar: [
                        new Ext.Button({
                            text: "Add",
                            listeners: {
                                click: onAddRepo
                            }
                        }),
                        new Ext.Button({
                            text: "Rename",
                            listeners: {
                                click: function() {
                                    var uri = getSelectedRepoURI();
                                    if (!uri) return;
                                    
                                    Addama.jcr.RepoManager.renameRepository({
                                        uri: uri,
                                        callback: function() {
                                            refreshRepoList();
                                        }
                                    });                                    
                                }
                            }
                        }),
                        new Ext.Button({
                            text: "Remove",
                            listeners: {
                                click: onRemoveRepo
                            }
                        })
                    ]
                },{
                    id: "repoPropsPanel",
                    title: "Properties",
                    region: "south",
                    split: true,
                    width: 200,
                    height: 150,
                    items: [
                        new Ext.form.FieldSet({
                            autoHeight: true,
                            border: false,
                            items: [
                                new Ext.form.TextField({
                                    id: "repoNameProp",
                                    fieldLabel: "Name",
                                    readOnly: true,
                                    style: readOnlyStyle,
                                    width: 150,
                                    grow: true,
                                    growMin: 150
                                }),
                                new Ext.form.TextField({
                                    id: "repoSessionProp",
                                    fieldLabel: "Session",
                                    readOnly: true,
                                    style: readOnlyStyle,
                                    width: 150,
                                    grow: true,
                                    growMin: 150
                                }),
                                new Ext.form.TextField({
                                    id: "repoUsernameProp",
                                    fieldLabel: "Username",
                                    readOnly: true,
                                    style: readOnlyStyle,
                                    width: 150,
                                    grow: true,
                                    growMin: 150
                                }),
                                new Ext.form.TextField({
                                    id: "repoPasswordProp",
                                    fieldLabel: "Password",
                                    readOnly: true,
                                    style: readOnlyStyle,
                                    width: 150,
                                    grow: true,
                                    growMin: 150
                                })
                            ]
                        })
                    ]
                }]
            });
        },

        init: function() {
            Ext.Ajax.request({
                url: "/addama-rest/primary-repo/path/sessions/isExisting",
                method: "get",
                success: Addama.jcr.RepoManager.loadRepositories,
                failure: Addama.jcr.RepoManager.createSessionNode
            })
        },

        createSessionNode: function() {
            Ext.Ajax.request({
                url: "/addama-rest/primary-repo/path/sessions/create",
                method: "post",
                success: Addama.jcr.RepoManager.loadRepositories,
                failure: Addama.jcr.RepoManager.loadRepositories
            });
        }
    };
}();
